import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 设置控制器 - 管理应用配置和用户偏好
/// Settings Controller - Manages application configuration and user preferences
class SettingsController extends GetxController {

  // 响应式状态 Reactive States
  final RxBool isDarkMode = false.obs;
  final RxString currentLanguage = '中文'.obs;
  final RxString currentFontSize = '标准'.obs;
  final RxDouble fontScale = 1.0.obs;

  // 语言选项 Language Options
  final Map<String, String> languageOptions = {
    '中文': 'zh_CN',
    'English': 'en_US',
    '日本語': 'ja_JP',
    '한국어': 'ko_KR',
  };

  // 字体大小选项 Font Size Options
  final Map<String, double> fontSizeOptions = {
    '小': 0.8,
    '标准': 1.0,
    '大': 1.2,
    '特大': 1.4,
  };

  @override
  void onInit() {
    super.onInit();
    _loadSettings();
  }

  /// 加载设置 Load Settings
  void _loadSettings() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      
      // 加载深色模式设置 Load dark mode setting
      isDarkMode.value = prefs.getBool('dark_mode') ?? false;
      
      // 加载语言设置 Load language setting
      final languageCode = prefs.getString('language') ?? 'zh_CN';
      currentLanguage.value = languageOptions.entries
          .firstWhere((entry) => entry.value == languageCode,
              orElse: () => const MapEntry('中文', 'zh_CN'))
          .key;
      
      // 加载字体大小设置 Load font size setting
      fontScale.value = prefs.getDouble('font_scale') ?? 1.0;
      currentFontSize.value = fontSizeOptions.entries
          .firstWhere((entry) => entry.value == fontScale.value,
              orElse: () => const MapEntry('标准', 1.0))
          .key;
      
      // 应用主题设置 Apply theme settings
      _applyTheme();
    } catch (e) {
      print('加载设置失败: $e');
    }
  }

  /// 应用主题 Apply Theme
  void _applyTheme() {
    Get.changeThemeMode(isDarkMode.value ? ThemeMode.dark : ThemeMode.light);
  }

  /// 切换深色模式 Toggle Dark Mode
  void toggleDarkMode(bool value) async {
    try {
      isDarkMode.value = value;
      _applyTheme();
      
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool('dark_mode', value);
      
      Get.snackbar(
        '主题已切换',
        value ? '已切换到深色模式' : '已切换到浅色模式',
        snackPosition: SnackPosition.TOP,
        backgroundColor: value ? Colors.grey.shade800 : Colors.blue,
        colorText: Colors.white,
      );
    } catch (e) {
      Get.snackbar(
        '设置失败',
        '主题切换失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 显示语言选择对话框 Show Language Dialog
  void showLanguageDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('选择语言'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: languageOptions.entries.map((entry) {
            return RadioListTile<String>(
              title: Text(entry.key),
              value: entry.key,
              groupValue: currentLanguage.value,
              onChanged: (value) {
                if (value != null) {
                  _changeLanguage(value);
                  Get.back();
                }
              },
            );
          }).toList(),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 更改语言 Change Language
  void _changeLanguage(String language) async {
    try {
      currentLanguage.value = language;
      final languageCode = languageOptions[language] ?? 'zh_CN';
      
      // 更新GetX语言设置 Update GetX language setting
      final locale = _getLocaleFromCode(languageCode);
      Get.updateLocale(locale);
      
      // 保存设置 Save setting
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('language', languageCode);
      
      Get.snackbar(
        '语言已更改',
        '应用语言已切换到$language',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    } catch (e) {
      Get.snackbar(
        '设置失败',
        '语言切换失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 从语言代码获取Locale Get Locale from Language Code
  Locale _getLocaleFromCode(String code) {
    switch (code) {
      case 'zh_CN':
        return const Locale('zh', 'CN');
      case 'en_US':
        return const Locale('en', 'US');
      case 'ja_JP':
        return const Locale('ja', 'JP');
      case 'ko_KR':
        return const Locale('ko', 'KR');
      default:
        return const Locale('zh', 'CN');
    }
  }

  /// 显示字体大小选择对话框 Show Font Size Dialog
  void showFontSizeDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('选择字体大小'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: fontSizeOptions.entries.map((entry) {
            return RadioListTile<String>(
              title: Text(
                entry.key,
                style: TextStyle(fontSize: 16 * entry.value),
              ),
              value: entry.key,
              groupValue: currentFontSize.value,
              onChanged: (value) {
                if (value != null) {
                  _changeFontSize(value);
                  Get.back();
                }
              },
            );
          }).toList(),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 更改字体大小 Change Font Size
  void _changeFontSize(String size) async {
    try {
      currentFontSize.value = size;
      fontScale.value = fontSizeOptions[size] ?? 1.0;
      
      // 保存设置 Save setting
      final prefs = await SharedPreferences.getInstance();
      await prefs.setDouble('font_scale', fontScale.value);
      
      Get.snackbar(
        '字体大小已更改',
        '字体大小已设置为$size',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    } catch (e) {
      Get.snackbar(
        '设置失败',
        '字体大小设置失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 运行网络诊断 Run Network Diagnostic
  void runNetworkDiagnostic() async {
    try {
      Get.dialog(
        const AlertDialog(
          title: Text('网络诊断'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('正在检查网络连接...'),
            ],
          ),
        ),
        barrierDismissible: false,
      );

      // 简单的网络连接测试 Simple network connection test
      bool isConnected = false;
      try {
        // 这里可以添加实际的网络测试逻辑
        await Future.delayed(const Duration(seconds: 1));
        isConnected = true;
      } catch (e) {
        isConnected = false;
      }
      
      Get.back(); // 关闭诊断对话框 Close diagnostic dialog
      
      // 显示诊断结果 Show diagnostic results
      Get.dialog(
        AlertDialog(
          title: const Text('网络诊断结果'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildDiagnosticItem(
                '网络连接',
                isConnected ? '正常' : '异常',
                isConnected ? Colors.green : Colors.red,
              ),
              const SizedBox(height: 8),
              _buildDiagnosticItem(
                '网络状态',
                '已连接',
                Colors.blue,
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('确定'),
            ),
          ],
        ),
      );
    } catch (e) {
      Get.back(); // 确保关闭加载对话框 Ensure loading dialog is closed
      Get.snackbar(
        '诊断失败',
        '网络诊断失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 构建诊断项 Build Diagnostic Item
  Widget _buildDiagnosticItem(String label, String value, Color color) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            value,
            style: TextStyle(
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }

  /// 清除缓存 Clear Cache
  void clearCache() {
    Get.dialog(
      AlertDialog(
        title: const Text('清除缓存'),
        content: const Text('确定要清除所有缓存数据吗？这将删除临时文件和图片缓存。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Get.back();
              try {
                // 这里可以添加实际的缓存清理逻辑
                // Here you can add actual cache clearing logic
                await Future.delayed(const Duration(seconds: 1));
                
                Get.snackbar(
                  '缓存已清除',
                  '应用缓存已成功清除',
                  snackPosition: SnackPosition.TOP,
                  backgroundColor: Colors.green,
                  colorText: Colors.white,
                );
              } catch (e) {
                Get.snackbar(
                  '清除失败',
                  '缓存清除失败: $e',
                  snackPosition: SnackPosition.TOP,
                  backgroundColor: Colors.red,
                  colorText: Colors.white,
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 备份数据 Backup Data
  void backupData() {
    Get.snackbar(
      '功能开发中',
      '数据备份功能正在开发中，敬请期待',
      snackPosition: SnackPosition.TOP,
      backgroundColor: Colors.orange,
      colorText: Colors.white,
    );
  }

  /// 显示应用信息 Show App Info
  void showAppInfo() {
    Get.dialog(
      AlertDialog(
        title: const Text('应用信息'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('应用名称: 游戏Wiki助手'),
            SizedBox(height: 8),
            Text('版本号: 1.0.0'),
            SizedBox(height: 8),
            Text('构建号: 1'),
            SizedBox(height: 8),
            Text('开发者: Wiki团队'),
            SizedBox(height: 8),
            Text('更新时间: 2024-01-01'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示帮助 Show Help
  void showHelp() {
    Get.dialog(
      AlertDialog(
        title: const Text('帮助与支持'),
        content: const SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '常见问题:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('1. 如何使用搜索功能？'),
            Text('   在首页搜索框输入关键词即可搜索相关Wiki'),
              SizedBox(height: 8),
              Text('2. 如何收藏Wiki页面？'),
              Text('   在Wiki页面点击收藏按钮即可'),
              SizedBox(height: 8),
              Text('3. 如何切换语言？'),
              Text('   进入设置 > 外观设置 > 语言设置'),
              SizedBox(height: 16),
              Text(
                '联系我们:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('邮箱: support@wikigame.com'),
              Text('QQ群: 123456789'),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示隐私政策 Show Privacy Policy
  void showPrivacyPolicy() {
    Get.dialog(
      AlertDialog(
        title: const Text('隐私政策'),
        content: const SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '数据收集:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('• 我们不会收集您的个人敏感信息'),
              Text('• 仅收集必要的使用统计数据以改善服务'),
              Text('• 收藏和历史记录仅存储在本地设备'),
              SizedBox(height: 16),
              Text(
                '数据使用:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('• 用于提供个性化的Wiki推荐'),
              Text('• 用于改善应用性能和用户体验'),
              Text('• 不会与第三方分享您的个人数据'),
              SizedBox(height: 16),
              Text(
                '数据安全:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('• 采用加密技术保护数据传输'),
              Text('• 定期更新安全措施'),
              Text('• 您可以随时删除本地数据'),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}